package com.star.ms.common.entity;

import com.alibaba.fastjson.JSONObject;
import com.star.ms.common.enums.HttpStatusEnum;
import lombok.Data;

import java.io.Serializable;

/**
 * Restful Response  RestFul风格的统一数据响应类
 * TODO 实现 前端和后端通过JSON数据的传输
 * @Time 2022/05/07
 */
@Data
public class RestResponse<T> implements Serializable {

    private Integer code;  // 响应的代码
    private String msg; // 响应的信息
    private T data;     // 响应的数据

    public RestResponse(){
    }
    public RestResponse(int code, String message, T data){
        this.code = code;
        this.setMsg(message);
        this.data = data;
    }
    public RestResponse(int code, T data){
        this.code = code;
        this.data = data;
    }
    public RestResponse(int code, String message){
        this.code = code;
        this.setMsg(message);
    }
    /**
     * 响应成功
     * @param data 响应的数据
     * @return  返回 对象
     * @param <T> 对象数据的类型
     */
    public static<T> RestResponse<T> success(T data){
        return new RestResponse<T>(200, null, data);
    }
    public static<T> RestResponse<T> success(String msg){
        return new RestResponse<T>(HttpStatusEnum.SUCCESS.code(), msg);
    }
    public static<T> RestResponse<T> success(String msg, T data){
        return new RestResponse<T>(HttpStatusEnum.SUCCESS.code(), msg, data);
    }
    public static<T> RestResponse<T> success(){
        return new RestResponse<T>(HttpStatusEnum.SUCCESS.code(), "");
    }

    /**
     * 响应失败
     * @param msg 返回的消息
     * @return 返回对象
     * @param <T> 标记的对象的类型 这里可省略
     */
    public static<T> RestResponse<T> fail(String msg){
        return new RestResponse<T>(HttpStatusEnum.FAIL.code(), msg, null);
    }
    public static<T> RestResponse<T> fail(int code, String msg){
        return new RestResponse<T>(code, msg, null);
    }
    public static<T> RestResponse<T> fail(){
        return new RestResponse<T>(HttpStatusEnum.FAIL.code(), "", null);
    }

    /**
     * 自定义状态的响应
     * @return
     */
    public static<T> RestResponse<T> custom(int code, String msg, T data){
        return  new RestResponse<T>(code, msg, data);
    }
    @Override
    public String toString() {
        return JSONObject.toJSONString(this);
    }
}


